﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BUS;
using DTO;
namespace QuanLyBanHang_N3A
{
    public partial class FormBanHang : Form
    {
        public FormBanHang()
        {
            InitializeComponent();
        }
        public string MaNV;

        void LayThongTinSanPham()
        {
            List<SanPhamDTO> ds = new List<SanPhamDTO>();
            SanPhamBUS bus = new SanPhamBUS();
            ds = bus.LayThongTinSanPham();
            colMaSP.DataSource = ds;
            colMaSP.DisplayMember = "MaSP";
            colMaSP.ValueMember = "MaSP";
        }
        int LaySoLuongTon(string MaSP)
        {
            SanPhamBUS bus = new SanPhamBUS();
            return bus.LaySoLuongTon(MaSP);
        }
        void LayThongTinKhachHang()
        {
            List<KhachHangDTO> ds = new List<KhachHangDTO>();
            KhachHangBUS bus = new KhachHangBUS();
            ds = bus.LayThongTinKH();
            cmbMaKH.DataSource = ds;
            cmbMaKH.DisplayMember = "TenKH";
            cmbMaKH.ValueMember = "MaKH";
            cmbMaKH.SelectedValue = "";
            cmbMaKH.SelectedText = "";
        }

        int LayLoaiKhachHang(string MaKH)
        {
            KhachHangBUS bus = new KhachHangBUS();
            return bus.LayLoaiKhachHang(MaKH);
        }
        string LayDiaChiKhachHang(string MaKH)
        {
            KhachHangBUS bus = new KhachHangBUS();
            return bus.LayDiaChiKhachHang(MaKH);
        }
        string LayDienThoaiKhachHang(string MaKH)
        {
            KhachHangBUS bus = new KhachHangBUS();
            return bus.LayDienThoaiKhachHang(MaKH);
        }
        //void LayThongTinKhachHangTheoLoai(int LoaiKH)// chua dung toi
        //{
        //    List<KhachHangDTO> ds = new List<KhachHangDTO>();
        //    KhachHangBUS bus = new KhachHangBUS();
        //    ds = bus.LayThongTinKhachHangTheoLoai(LoaiKH);
        //    cmbMaKH.DataSource = ds;
        //    cmbMaKH.DisplayMember = "TenKH";
        //    cmbMaKH.ValueMember = "MaKH";
        //}
        string LayTenSanPham(string maSP)
        {
            List<SanPhamDTO> ds = new List<SanPhamDTO>();
            SanPhamBUS bus = new SanPhamBUS();
            ds = bus.LayThongTinSanPham(maSP);
            return ds[0].TenSP.ToString();
        }
        int LayDonGia(string maSP)
        {
            List<SanPhamDTO> ds = new List<SanPhamDTO>();
            SanPhamBUS bus = new SanPhamBUS();
            ds = bus.LayThongTinSanPham(maSP);
            return ds[0].DonGia;
        }
        int LayCVSP(string maSP)
        {
            List<SanPhamDTO> ds = new List<SanPhamDTO>();
            SanPhamBUS bus = new SanPhamBUS();
            ds = bus.LayThongTinSanPham(maSP);
            return ds[0].CV_SP;
        }
        void LoadDonHang(ref double tongtien, ref int tongcv)
        {
            tongtien = 0;
            tongcv = 0;
            for (int i = 0; i < GridViewSanPham.Rows.Count; i++)
            {
                if (GridViewSanPham.Rows[i].Cells[4].Value == null)
                    return;

                double dongia = Convert.ToDouble(LayDonGia(GridViewSanPham.Rows[i].Cells[1].Value.ToString()));
                int cvSP = Convert.ToInt32(LayCVSP(GridViewSanPham.Rows[i].Cells[1].Value.ToString()));
                if (rdKHBT.Checked == true)
                    dongia = dongia + (dongia * (10.0 / 100));

                double thanhtien = Convert.ToDouble(GridViewSanPham.Rows[i].Cells[3].Value) * dongia;
                int diem = Convert.ToInt32(GridViewSanPham.Rows[i].Cells[3].Value) * cvSP;
                GridViewSanPham.Rows[i].Cells[4].Value = dongia.ToString();
                GridViewSanPham.Rows[i].Cells[5].Value = thanhtien.ToString();
                tongtien += thanhtien;
                tongcv += diem;
                // MessageBox.Show(tongtien.ToString());
                // lbTongTien.Text = tongtien.ToString();
            }

        }
        string LayTenNhanVien(string maNV)
        {
            List<NhanVienDTO> ds = new List<NhanVienDTO>();
            NhanVienBUS bus = new NhanVienBUS();
            ds = bus.LayThongTinNhanVien(MaNV);
            return ds[0].TenNV.ToString();
        }
        string KhoiTaoMaCTBH()
        {
            CTPhieuBanBUS bus = new CTPhieuBanBUS();
            return bus.TaoCTHDMoi();
        }
        string KhoiTaoMaBH()
        {
            PhieuBanBUS bus = new PhieuBanBUS();
            return bus.TaoMaBHMoi();
        }
        string KhoiTaoMaKH()
        {
            KhachHangBUS bus = new KhachHangBUS();
            return bus.MaKHMoi();
        }

        private void FormBanHang_Load(object sender, EventArgs e)
        {
            rdKHBT.Checked = true;
            rdLanDau.Checked = true;
            lbTongTien.Text = "0";
            lbTongCV.Text = "0";
            txtTenKH.Text = "";
            lbTenNV.Text = LayTenNhanVien(MaNV);
            DateTime dt = DateTime.Now;
            lbNgayBan.Text = dt.ToString("dd/MM/yyyy");

            lbMaBH.Text = KhoiTaoMaBH().Trim();
            LayThongTinSanPham();
            this.GridViewSanPham.Rows.Clear();
        }

        private void btThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void rdKHBT_CheckedChanged(object sender, EventArgs e)
        {
            if (rdKHBT.Checked == true)
            {
                double tongtien = 0;
                int tongcv = 0;
                LoadDonHang(ref tongtien, ref tongcv);
                lbTongTien.Text = tongtien.ToString();
                lbTongCV.Text = tongcv.ToString();

                lbTongCV.Visible = false;
                lbDiemCV.Visible = false;
                if (cmbMaKH.SelectedIndex < 0)
                    return;
            }
        }

        private void rdKHTV_CheckedChanged(object sender, EventArgs e)
        {
            if (rdKHTV.Checked == true)
            {
                double tongtien = 0;
                int tongcv = 0;
                lbTongCV.Visible = true;
                lbDiemCV.Visible = true;
                LoadDonHang(ref tongtien, ref tongcv);
                lbTongTien.Text = tongtien.ToString();
                lbTongCV.Text = tongcv.ToString();
                if (cmbMaKH.SelectedIndex < 0)
                    return;
            }
        }

        private void GridViewSanPham_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            // 0      1     2        3         4            5 
            //stt   masp  tensp   soluong    dongia     thanhtien
            if (e.RowIndex < 0)
                return;
            if (GridViewSanPham.Rows[e.RowIndex].Cells[1].Value == null)
                return;
            string tenSP = LayTenSanPham(GridViewSanPham.Rows[e.RowIndex].Cells[1].Value.ToString());

            int SLTon = LaySoLuongTon(GridViewSanPham.Rows[e.RowIndex].Cells[1].Value.ToString());

            // kiem tra số luong ton trong kho
            if (SLTon <= 0)
            {
                MessageBox.Show("THÔNG BÁO!\r\n\n\t Sản Phẩm " + tenSP.ToString() + "\r\n\n\t\t Hết hàng!");
                return;
            }
            if (tenSP == "")
                return;
            double dongia = Convert.ToDouble(LayDonGia(GridViewSanPham.Rows[e.RowIndex].Cells[1].Value.ToString()));

            int cvSP = Convert.ToInt32(LayCVSP(GridViewSanPham.Rows[e.RowIndex].Cells[1].Value.ToString()));

            if (rdKHBT.Checked == true)
                dongia = dongia + (dongia * (10.0 / 100));

            this.GridViewSanPham.Rows[e.RowIndex].Cells[2].Value = tenSP;
            this.GridViewSanPham.Rows[e.RowIndex].Cells[4].Value = dongia;


            string soluong = GridViewSanPham.Rows[e.RowIndex].Cells[3].Value.ToString();

            //Kiểm tra số lượng tồn trong kho và số lượng nhập vào

            if (Convert.ToInt32(soluong) > SLTon)
            {
                MessageBox.Show("Số lượng trong kho còn: " + SLTon.ToString());
                soluong = "0";
                GridViewSanPham.Rows[e.RowIndex].Cells[3].Value = 0;
                return;
            }

            this.GridViewSanPham.Rows[e.RowIndex].Cells[7].Value = SLTon - Convert.ToInt32(soluong);

            double thanhtien = Convert.ToDouble(soluong) * dongia;
            int diem = Convert.ToInt32(soluong) * cvSP;
            this.GridViewSanPham.Rows[e.RowIndex].Cells[6].Value = diem;
            this.GridViewSanPham.Rows[e.RowIndex].Cells[5].Value = thanhtien;
            double tongtien = 0;
            int tongcv = 0;
            for (int i = 0; i < this.GridViewSanPham.Rows.Count; i++)
            {
                tongtien += Convert.ToDouble(this.GridViewSanPham.Rows[i].Cells[5].Value);
                tongcv += Convert.ToInt32(this.GridViewSanPham.Rows[i].Cells[6].Value);
            }
            lbTongTien.Text = tongtien.ToString();
            lbTongCV.Text = tongcv.ToString();
        }

        private void GridViewSanPham_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;
            this.GridViewSanPham.Rows[e.RowIndex].Cells[0].Value = e.RowIndex + 1;
        }

        private void GridViewSanPham_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.RowIndex < 0)
                return;
            GridViewSanPham.Rows[e.RowIndex].Cells[3].Value = 0;// số lượng
        }

        private void btHuy_Click(object sender, EventArgs e)
        {
            this.GridViewSanPham.Rows.Clear();
            this.lbTongTien.Text = "0";
            this.lbTongCV.Text = "0";
            DateTime dt = DateTime.Now;
            lbNgayBan.Text = dt.ToString("dd/MM/yyyy");
            rdKHBT.Checked = true;
        }

        private void btBanHang_Click(object sender, EventArgs e)
        {
            string MaKH = "";

            if (rdLanDau.Checked == true)
            {
                if (txtTenKH.Text == "")
                {
                    MessageBox.Show("Chưa Nhập Thông Tin Khách Hàng");
                    txtTenKH.SelectAll();
                    txtTenKH.Focus();
                    return;
                }
                MaKH = KhoiTaoMaKH().Trim();
                KhachHangDTO khDTO = new KhachHangDTO();
                khDTO.MaKH = MaKH.Trim();
                khDTO.TenKH = txtTenKH.Text.Trim();
                khDTO.DThoai = txtSoDT.Text.Trim();
                khDTO.DiaChi = txtDiaChi.Text.Trim();
                khDTO.GioiTinh = " ";
                khDTO.TongCV = 0;

                khDTO.TongTienThanhToan = 0;
                if (rdKHTV.Checked == true)
                    khDTO.LoaiKH = 1;
                else
                    khDTO.LoaiKH = 0;

                KhachHangBUS khBUS = new KhachHangBUS();
                khBUS.ThemKhachHang(khDTO);
            }

            if (rdNhieuLan.Checked == true)
            {
                if (cmbMaKH.Text == "")
                {
                    MessageBox.Show("Chưa Nhập Thông Tin Khách Hàng");
                    cmbMaKH.Select();
                    cmbMaKH.Focus();
                    return;
                }
                MaKH = cmbMaKH.SelectedValue.ToString();
            }
            // phieu ban
            PhieuBanDTO pbDTO = new PhieuBanDTO();
            pbDTO.MaBH = lbMaBH.Text.Trim();
            DateTime ngayban = DateTime.ParseExact(this.lbNgayBan.Text, "dd/MM/yyyy", null);
            pbDTO.NgayBH = ngayban;
            pbDTO.MaNV = MaNV.Trim();
            pbDTO.TongTien = Convert.ToDouble(lbTongTien.Text.ToString());
            PhieuBanBUS pdbus = new PhieuBanBUS();
            pdbus.ThemPhieuBan(pbDTO);

            // 0      1     2        3         4            5 
            //stt   masp  tensp   soluong    dongia     thanhtien

            //CTPhieuBan
            for (int i = 0; i < this.GridViewSanPham.Rows.Count - 1; i++)
            {
                CTPhieuBanDTO ctpbDTO = new CTPhieuBanDTO();
                ctpbDTO.MaCTPB = KhoiTaoMaCTBH().ToString(); ;
                ctpbDTO.MaBH = lbMaBH.Text.Trim();
                ctpbDTO.MaSP = GridViewSanPham.Rows[i].Cells[1].Value.ToString();
                ctpbDTO.MaKH = MaKH.Trim();
                ctpbDTO.SLBan = Convert.ToInt32(GridViewSanPham.Rows[i].Cells[3].Value);
                ctpbDTO.DonGia = Convert.ToDouble(GridViewSanPham.Rows[i].Cells[4].Value);
                ctpbDTO.ThanhTien = Convert.ToDouble(GridViewSanPham.Rows[i].Cells[5].Value);
                CTPhieuBanBUS ctpbbus = new CTPhieuBanBUS();
                ctpbbus.ThemCTPhieuBan(ctpbDTO);
            }
            // san pham
            for (int i = 0; i < this.GridViewSanPham.Rows.Count - 1; i++)
            {
                SanPhamBUS spbus = new SanPhamBUS();
                string MaSP = GridViewSanPham.Rows[i].Cells[1].Value.ToString();
                int SLTon = Convert.ToInt32(this.GridViewSanPham.Rows[i].Cells[7].Value);
                spbus.CapNhatSoLuongSanPham(SLTon, MaSP);
            }
            // khach hang
            if (rdKHTV.Checked == true)
            {
                KhachHangBUS khBUS1 = new KhachHangBUS();
                int diencv = khBUS1.LayDiemCV(MaKH);
                diencv = diencv + Convert.ToInt32(lbTongCV.Text);
                khBUS1.CapNhatDiemCV(diencv, MaKH);
            }
            FormReportHoaDonBanHang frm = new FormReportHoaDonBanHang();
            frm.MaBH = lbMaBH.Text.Trim();
            frm.ShowDialog();

            this.FormBanHang_Load(sender, e);

        }

        private void rdLanDau_CheckedChanged(object sender, EventArgs e)
        {

            txtTenKH.Visible = true;
            cmbMaKH.Visible = false;
            cmbMaKH.SelectedText = "";
            txtTenKH.Text = "";
            txtSoDT.Text = "";
            txtDiaChi.Text = "";
            rdKHBT.Enabled = true;
            rdKHTV.Enabled = false;
            rdKHBT.Checked = true;
            txtSoDT.Enabled = true;
            txtDiaChi.Enabled = true;
        }

        private void rdNhieuLan_CheckedChanged(object sender, EventArgs e)
        {
            LayThongTinKhachHang();
            txtTenKH.Visible = false;
            cmbMaKH.Visible = true;
            txtTenKH.Text = " ";
            txtSoDT.Text = " ";
            txtDiaChi.Text = " ";
            txtSoDT.Enabled = false;
            txtDiaChi.Enabled = false;
            //lbDiemCV.Visible = false;

        }

        private void cmbMaKH_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbMaKH.SelectedIndex < 0)
                return;
            int LoaiKH = LayLoaiKhachHang(cmbMaKH.SelectedValue.ToString());

            if (LoaiKH == 0)
            {
                rdKHBT.Checked = true;
            }
            else
            {
                rdKHTV.Checked = true;
            }

            rdKHBT.Enabled = false;
            rdKHTV.Enabled = false;
            if (cmbMaKH.SelectedValue.ToString() == "DTO.KhachHangDTO")
                return;
            txtDiaChi.Text = LayDiaChiKhachHang(cmbMaKH.SelectedValue.ToString()).Trim();
            txtSoDT.Text = LayDienThoaiKhachHang(cmbMaKH.SelectedValue.ToString()).Trim();
        }

        private void txtSoDT_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void txt_KeyPress(object sender, KeyPressEventArgs e)
        {
            //Kim tra
            TextBox txt = sender as TextBox;
            if (txt.Name == "Column3")
            {
                //Là các ký tự số hoặc điều khiển
                if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar))
                {
                    e.Handled = false;
                }
                else
                {
                    e.Handled = true;
                }
            }
        }

        private void txt_Validating(object sender, CancelEventArgs e)
        {
            TextBox txt = sender as TextBox;
            if (txt.Name == "Column3")
            {
                try
                {

                }
                catch
                {
                    MessageBox.Show("Bạn phải nhập vào dữ liệu kiểu số.");
                }
            }
        }

        private void GridViewSanPham_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (this.GridViewSanPham.CurrentCellAddress.X == GridViewSanPham.Columns[3].DisplayIndex)
            {
                TextBox txt = e.Control as TextBox;
                if(GridViewSanPham.RowCount<0)
                    return;
                txt.Name = "Column3";
                if (txt != null)
                {
                    txt.KeyPress -= new KeyPressEventHandler(txt_KeyPress);
                    txt.KeyPress += new KeyPressEventHandler(txt_KeyPress);
                    txt.Validating -= new CancelEventHandler(txt_Validating);
                    txt.Validating += new CancelEventHandler(txt_Validating);
                }
            }

            
        }

        private void txtSoDT_TextChanged(object sender, EventArgs e)
        {

        }

    }
}
